import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || 'http://localhost:3001/api',
  timeout: 30000, // 超时时间30秒
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器 - 可以在这里添加认证信息等
api.interceptors.request.use(
  config => {
    // 记录请求日志
    console.log(`API请求: ${config.method.toUpperCase()} ${config.url}`, config.data || '');
    return config;
  },
  error => {
    console.error('API请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 统一处理错误
api.interceptors.response.use(
  response => {
    // 记录响应日志
    console.log(`API响应: ${response.status} ${response.config.url}`, response.headers);
    return response.data;
  },
  error => {
    console.error('API响应错误:', error.response?.status || 'Unknown', error.message);
    return Promise.reject(error);
  }
);

// API基础URL
const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3001/api';

// 小说相关API
export const novelsApi = {
  // 获取所有小说
  getAll: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/novels`);
      if (!response.ok) throw new Error('获取小说列表失败');
      return await response.json();
    } catch (error) {
      console.error('获取小说列表失败:', error);
      throw error;
    }
  },
  
  // 获取单本小说信息
  getNovel: async (id) => {
    try {
      const response = await fetch(`${API_BASE_URL}/novels/${id}`);
      if (!response.ok) throw new Error('获取小说信息失败');
      return await response.json();
    } catch (error) {
      console.error('获取小说信息失败:', error);
      throw error;
    }
  },
  
  // 获取完整小说内容
  async getFullNovelContent(id, options = {}) {
    try {
      if (!id) {
        throw new Error('无效的小说ID');
      }

      // 构建URL，添加编码参数
      let url = `${API_BASE_URL}/novels/${id}/content`;
      if (options.encoding) {
        url += `?encoding=${options.encoding}`;
      }

      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`获取小说内容失败 (状态码: ${response.status})`);
      }
      
      const data = await response.json();
      return data;
    } catch (error) {
      console.error('获取小说完整内容失败:', error);
      throw error;
    }
  },
  
  // 获取小说内容分片 (保留用于兼容)
  getNovelChunk: async (id, chunkIndex, progressCallback, options = {}) => {
    try {
      // 构建URL，根据用户可能指定的编码添加参数
      let url = `${API_BASE_URL}/novels/${id}/chunks/${chunkIndex}`;
      if (options.encoding) {
        url += `?encoding=${options.encoding}`;
      }
      
      const response = await fetch(url);
      if (!response.ok) throw new Error(`获取小说分片 ${chunkIndex} 失败`);
      
      const reader = response.body.getReader();
      const contentLength = +response.headers.get('Content-Length');
      let receivedLength = 0;
      let chunks = [];
      
      while(true) {
        const {done, value} = await reader.read();
        
        if (done) {
          break;
        }
        
        chunks.push(value);
        receivedLength += value.length;
        
        if (progressCallback && contentLength) {
          progressCallback(value, receivedLength, contentLength);
        }
      }
      
      let chunksAll = new Uint8Array(receivedLength);
      let position = 0;
      for(let chunk of chunks) {
        chunksAll.set(chunk, position);
        position += chunk.length;
      }
      
      const result = new TextDecoder("utf-8").decode(chunksAll);
      try {
        return JSON.parse(result);
      } catch (e) {
        return { data: result };
      }
    } catch (error) {
      console.error(`获取小说分片 ${chunkIndex} 失败:`, error);
      throw error;
    }
  },
  
  // 触发扫描
  triggerScan: async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/novels/scan`, {
        method: 'POST'
      });
      if (!response.ok) throw new Error('触发扫描失败');
      return await response.json();
    } catch (error) {
      console.error('触发扫描失败:', error);
      throw error;
    }
  }
};

export default api; 